<?php

namespace app\api\controller;
use app\api\service\RoomService;
use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Lights;
use app\common\model\Occupants;
use app\common\model\Rooms;
use app\manystore\model\ManystoreShop;
use think\Db;

/**
 * 房间
 */
class Room extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Rooms();
    }

    /*
     * 包间大厅
     */
    public function room_list()
    {
        $where = []; // 初始化查询条件数组
        if (input('title') != null && input('title') != '') {
            $where['title|theme'] = ['like', '%' . input('title') . '%'];
        }
        $where['room_type'] = input('room_type');
        if (input('shop_id') != null && input('shop_id') != '') {
            $where['shop_id'] = input('shop_id');
        } else {
            if (!$lights_id = input('lights_id')) {
                $this->error(__('请先绑定灯码'));
            }
            $lights = Lights::where('id', $lights_id)->find();
            if (!$lights) {
                $this->error(__('灯码不存在'));
            }
            $where['shop_id'] = $lights['shop_id'];

        }

        if(input('is_put')!=null&&input('is_put')!=''){
            //不接受拼桌 查询空闲的
            if(input('is_put')==0){
                $where['status']=['=',0];
            }else{
                //可接受的话 查询可接受的
                $where['status']=['in',[0,1]];
                $where['shared_table']=['=',1];
            }
        }
        $list = Rooms::where($where)
            ->field('id,title,deposit,theme,image_url,shop_id,capacity,shared_table,status')
            ->order('weigh desc')
            ->paginate(10);
        $server=new RoomService();
        $num=input('num','1');
        foreach ($list as $key => $item) {
            $in_count = $server->order_in($item['id'], $item['shop_id'], input('start_time'), input('end_time'));
            $item->left_count = $item['capacity'] - $in_count;  // 满员删掉
            if ($item->left_count < $num) {
                unset($list[$key]);  // 删除该项
            }

            //获取第一个的游玩时间
            $Occupants = Occupants::where('room_id', $item->id)->where('status', 0)->find();
            if ($Occupants) {
                if ($Occupants['reservations_id'] == '' || $Occupants['reservations_id'] == null) {
                    $item->time_slot = date('H:i', $Occupants['join_time']);
                } else {
                    $Reservations = \app\common\model\Reservations::where('id', $Occupants['reservations_id'])->find();
                    $item->time_slot = date('H:i', strtotime($Reservations['start_time'])) . '-' . date('H:i', strtotime($Reservations['end_time']));
                }
            } else {
                $item->time_slot = '';
            }

        }
        $list = array_values($list->items());
        $this->success('请求成功', $list);
    }

    /*
     * 包间详情
     */
    public function room_info() {
        if (!$id = input('id')) {
            $this->error(__('请选择包间'));
        }
        if (!$shop_id = input('shop_id')) {
            $this->error(__('请选择门店'));
        }
        // 获取时间参数，如果没有传入，则使用当前时间
        $start_time = input('start_time');
        $end_time = input('end_time');

        // 如果时间参数为空，则设置为当前时间
        if (empty($start_time) || empty($end_time)) {
            $current_time = date('Y-m-d H:i:s');
            $start_time = $current_time;
            $end_time = $current_time;
        }

        // 查询包间信息
        $info = Rooms::where('id', '=', $id)
            ->field('id,title,deposit,theme,carousel_images,capacity,shared_table')->find(); // 假设数据库中增加字段表示总可用位置

        if ($info) {
            $imagesArray = explode(',', $info['carousel_images']);
            $resultArray = [];
            foreach ($imagesArray as $url) {
                $resultArray[] = ['image' => trim($url)]; // 使用 trim 去除多余的空格
            }
            $info['carousel_images'] = $resultArray;
            $info['theme'] = $info['theme'] == "" ? '空' : $info['theme'];

            // 查找正在玩的人
            $occupants = Occupants::field('id')->with(['user'])->where('occupants.status', '<>', 2)
//                ->where('shop_id', '=', $shop_id)
                ->where('room_id',$id)
                ->select(); // 获取所有正在玩的用户

            // 查找已预约的人
            $reservations = Db::table('fa_reservations')
                ->where('start_time', '<', $end_time)
                ->where('end_time', '>', $start_time)
                ->where('room_id', '=', $info['id'])
                ->value('(number_of_people-number_used)') ?? 0; // 获取正在进行的预约

            // 获取正在玩的用户人数
            $occupied_count = count($occupants);
            $reserved_count = $reservations; // 预约人数

            // 获取空闲位置数量
            $total_positions = $info['capacity']; // 包间总位置
            $free_count = $total_positions - ($occupied_count + $reserved_count); // 计算空闲位置数

            // 构建返回的 occupants 信息
            $occupant_info = [];

            // 添加正在使用的用户
            foreach ($occupants as $occupant) {
                $occupant->getRelation('user')->visible(['username', 'avatar','id','link_img','gender']);
                $occupant_info[] = [
                    'user_info' => $occupant, // 用户信息
                    'status' => '正在使用' // 状态
                ];
            }

            // 添加已预约的用户
            for ($i = 0; $i<$reservations; $i++) {
                $occupant_info[] = [
                    'status' => '已预约' // 状态
                ];
            }
            // 添加空闲位置信息
            for ($i = 0; $i < $free_count; $i++) {
                $occupant_info[] = [
                    'status' => '空闲' // 状态
                ];
            }
            $server=new RoomService();
            $in_count = $server->order_in($id, $shop_id,$start_time, $end_time);
            $info['left_count'] = $info['capacity'] - $in_count;
            // 组合最终信息
            $info['occupants_info'] = $occupant_info; // 添加占用和空闲信息
            $info['occupied_count'] = $occupied_count; // 当前占用人数
            $info['reserved_count'] = $reserved_count; // 预约人数
            $info['free_count'] = $free_count; // 空闲位置数
        }

        $this->success('请求成功', $info);
    }


    public function saveroom_theme(){


        $room=  Rooms::where('id','=',input('id'))->find();
        if($room){
            Rooms::where('id','=',input('id'))->update(['theme'=>input('theme')]);

            $this->success('请求成功', []);
        }else{
            $this->error('此房间不存在');
        }
    }

    public function saveroom_shared_table(){
        $room=  Rooms::where('id','=',input('id'))->find();
        if($room){
            Rooms::where('id','=',input('id'))->update(['shared_table'=>input('shared_table')]);

            $this->success('请求成功', []);
        }else{
            $this->error('此房间不存在');
        }
    }



}
